package leetcode.D700.T637;

import util.TreeNode;

import java.util.ArrayList;
import java.util.List;

class Solution {
    private List<Double> result = new ArrayList<>();
    private List<Long> sum = new ArrayList<>();
    private List<Long> num = new ArrayList<>();
    public List<Double> averageOfLevels(TreeNode root) {
        tranverse(root, 0);
        for(int i=0; i<num.size(); ++i) {
            result.add(sum.get(i).doubleValue() / num.get(i).longValue());
        }
        return result;
    }
    private void tranverse(TreeNode root, int level) {
        if(root == null) return;
        if(level == sum.size()) {
            num.add(1L);
            sum.add((long)root.val);
        } else {
            // num.get(level) = num.get(level) + 1;
            num.set(level, num.get(level) + 1);
            // sum.get(level) = sum.get(level) + root.val;
            sum.set(level, sum.get(level) + root.val);
        }
        tranverse(root.left, level+1);
        tranverse(root.right, level+1);
    }
}